<?php

namespace app\admin\controller\shopro\user;

use addons\shopro\service\commission\Agent as AgentService;
use fast\Tree;
use think\Db;
use app\admin\controller\shopro\Common;
use addons\shopro\service\Wallet as WalletService;
use app\admin\model\shopro\user\User as UserModel;
use app\admin\model\shopro\user\Coupon as UserCouponModel;

class User extends Common
{
    protected $model = null;

    protected $noNeedRight = ['select'];

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new UserModel;
    }

    /**
     * 用户列表
     */
    public function index()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    /**
     * 用户详情
     *
     * @param  $id
     */
    public function detail($id)
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $user = $this->model->with(['third_oauth', 'parent_user'])->where('id', $id)->find();
        if (!$user) {
            $this->error(__('No Results were found'));
        }

        $this->success('获取成功', null, $user);
    }

    /**
     * 更新用户
     *
     * @param  $id
     * @return \think\Response
     */
    public function edit($id = null)
    {
        $params = $this->request->only(['username', 'nickname', 'mobile', 'password', 'avatar', 'gender', 'email', 'status']);

        if (empty($params['password'])) unset($params['password']);
        if (empty($params['username'])) unset($params['username']);

        $params['id'] = $id;
        $this->svalidate($params, '.edit');
        unset($params['id']);

        $user = $this->model->where('id', $id)->find();
        $user->save($params);

        $this->success('更新成功', null, $user);
    }

    /**
     * 删除用户(支持批量)
     *
     * @param  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        if (empty($id)) {
            $this->error(__('Parameter %s can not be empty', 'id'));
        }

        $id = explode(',', $id);
        $list = $this->model->where('id', 'in', $id)->select();
        $result = Db::transaction(function () use ($list) {
            $count = 0;
            foreach ($list as $item) {
                $count += $item->delete();
            }

            return $count;
        });

        if ($result) {
            $this->success('删除成功', null, $result);
        } else {
            $this->error(__('No rows were deleted'));
        }
    }

    public function recharge()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $params = $this->request->only(['id', 'type', 'amount', 'memo']);
        if (!in_array($params['type'], ['money', 'score'])) {
            error_stop('参数错误');
        }

        $result = Db::transaction(function () use ($params) {
            return WalletService::change($params['id'], $params['type'], $params['amount'], 'admin_recharge', [], $params['memo']);
        });
        if ($result) {
            $this->success('充值成功');
        }
        $this->error('充值失败');
    }


    /**
     * 用户优惠券列表
     */
    public function coupon($id)
    {
        $userCoupons = UserCouponModel::sheepFilter()->with('coupon')->where('user_id', $id)
            ->order('id', 'desc')->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $userCoupons);
    }


    public function select()
    {
        if (!$this->request->isAjax()) {
            return $this->view->fetch();
        }

        $data = $this->model->sheepFilter()->paginate($this->request->param('list_rows', 10));

        $this->success('获取成功', null, $data);
    }

    public function userTree()
    {
        // 获取全部用户信息
        $list = $this->model->field('id,parent_user_id,nickname,username,avatar,status')->select();
        $list = collection($list)->toArray();

        // 初始化树结构
        Tree::instance()->init($list, 'parent_user_id');

        // 生成树型结构（可以递归生成多级嵌套结构，指定根节点parent_id为0）
        $userTree = Tree::instance()->getTreeArray(0);
        
        // 计算每个节点的子节点总数
        $userTree = $this->calculateChildrenCount($userTree);
        
        // 如果是AJAX请求，返回HTML
        if ($this->request->isAjax()) {
            $html = $this->generateUserTreeHtml($userTree);
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        }
        
        // 如果不是AJAX请求，返回视图
        $this->view->assign('userTree', $userTree);
        return $this->view->fetch();
    }

    public function executeTestAll()
    {
        $userId = $this->request->get('user_id');
        $agent = new AgentService($userId);
        $agent->testAll($userId);
        echo 'kkkk';
        exit;
    }

    public function testCalculateScore()
    {
        $number = $this->request->get('n');
        if ($number < 1) {
            throw new \Exception('code数字不能小于1');
        } elseif ($number > 1000000) {
            throw new \Exception('code数字不能大于1000000');
        }

        $score = 0;

        if ($number <= 600000) {
            $score = 400 * (1 - 0.8 * ($number - 1) / 599999);
        } else {
            $score = 400 * (0.2 - 0.1 * ($number - 600000) / 400000);
        }

        echo $score;
        exit;
    }
    
    /**
     * 生成用户树HTML
     */
    public function userTreeHtml()
    {
        try {
            // 获取全部用户信息
            $list = $this->model->field('id,parent_user_id,nickname,username,avatar,status')->select();
            $list = collection($list)->toArray();

            // 初始化树结构
            Tree::instance()->init($list, 'parent_user_id');

            // 生成树型结构
            $userTree = Tree::instance()->getTreeArray(0);
            
            // 计算每个节点的子节点总数
            $userTree = $this->calculateChildrenCount($userTree);
            
            // 生成HTML
            $html = $this->generateUserTreeHtml($userTree);
            
            // 设置正确的Content-Type
            header('Content-Type: text/html; charset=utf-8');
            echo $html;
            exit;
        } catch (\Exception $e) {
            header('Content-Type: text/html; charset=utf-8');
            echo '<div class="alert alert-danger">错误: ' . $e->getMessage() . '</div>';
            exit;
        }
    }
    
    /**
     * 递归生成用户树HTML
     */
    private function generateUserTreeHtml($tree, $level = 0)
    {
        $html = '';
        foreach ($tree as $user) {
            $hasChildren = !empty($user['childlist']) && count($user['childlist']) > 0;
            $statusClass = $user['status'] === 'normal' ? 'status-normal' : 'status-disabled';
            $statusText = $user['status'] === 'normal' ? '正常' : '禁用';
            
            $html .= '<div class="tree-item level-' . $level . '">';
            $html .= '<div class="tree-item-content">';
            
            // 展开/收起按钮
            if ($hasChildren) {
                $html .= '<div class="tree-toggle" onclick="toggleNode(this)">';
                $html .= '<i class="fa fa-chevron-right"></i>';
                $html .= '</div>';
            } else {
                $html .= '<div class="tree-toggle-placeholder"></div>';
            }
            
            // 用户头像
            $html .= '<div class="user-avatar">';
            if ($user['avatar']) {
                $html .= '<img src="' . $user['avatar'] . '" alt="' . $user['nickname'] . '">';
            } else {
                $html .= '<div class="avatar-placeholder">' . mb_substr($user['nickname'], 0, 1) . '</div>';
            }
            $html .= '</div>';
            
            // 用户信息
            $html .= '<div class="user-details">';
            $html .= '<div class="user-name">';
            $html .= '<span class="nickname">' . $user['nickname'] . '</span>';
            $html .= '<span class="username">(' . $user['username'] . ')</span>';
            $html .= '<span class="user-id">#' . $user['id'] . '</span>';
            $html .= '</div>';
            
            $html .= '<div class="user-stats">';
            $html .= '<span class="badge ' . $statusClass . '">' . $statusText . '</span>';
            if ($user['children_count'] > 0) {
                $html .= '<span class="badge badge-info">直推: ' . $user['children_count'] . '人</span>';
            }
            if ($user['total_descendants'] > 0) {
                $html .= '<span class="badge badge-warning">团队: ' . $user['total_descendants'] . '人</span>';
            }
            $html .= '</div>';
            $html .= '</div>';
            
            // 操作按钮
            $html .= '<div class="user-actions">';
            $html .= '<button class="btn btn-primary btn-sm" onclick="viewUserDetail(' . $user['id'] . ')">';
            $html .= '<i class="fa fa-eye"></i> 查看详情';
            $html .= '</button>';
            $html .= '</div>';
            
            $html .= '</div>';
            
            // 子节点
            if ($hasChildren) {
                $html .= '<div class="tree-children">';
                $html .= $this->generateUserTreeHtml($user['childlist'], $level + 1);
                $html .= '</div>';
            }
            
            $html .= '</div>';
        }
        
        return $html;
    }
    
    /**
     * 递归计算每个节点的子节点总数
     */
    private function calculateChildrenCount($tree)
    {
        foreach ($tree as &$node) {
            $node['children_count'] = 0;
            if (!empty($node['childlist'])) {
                $node['children_count'] = count($node['childlist']);
                // 递归计算子节点的子节点数量
                $node['childlist'] = $this->calculateChildrenCount($node['childlist']);
                // 计算所有后代节点总数
                $node['total_descendants'] = $this->getTotalDescendants($node['childlist']);
            } else {
                $node['total_descendants'] = 0;
            }
        }
        return $tree;
    }
    
    /**
     * 递归计算所有后代节点总数
     */
    private function getTotalDescendants($childlist)
    {
        $total = 0;
        foreach ($childlist as $child) {
            $total += 1; // 当前节点
            if (!empty($child['childlist'])) {
                $total += $this->getTotalDescendants($child['childlist']);
            }
        }
        return $total;
    }
}
